package com.starblink.brand.detail.ui

import android.content.res.ColorStateList
import android.graphics.Color
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.request.RequestOptions
import com.google.android.material.appbar.AppBarLayout
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.bean.LoadAction
import com.starblink.android.basic.brv.PageRefreshLayout
import com.starblink.android.basic.brv.annotaion.DividerOrientation
import com.starblink.android.basic.brv.utils.bindingAdapter
import com.starblink.android.basic.brv.utils.divider
import com.starblink.android.basic.brv.utils.grid
import com.starblink.android.basic.brv.utils.linear
import com.starblink.android.basic.brv.utils.models
import com.starblink.android.basic.brv.utils.setup
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.color
import com.starblink.android.basic.ext.commContext
import com.starblink.android.basic.ext.disableCorner
import com.starblink.android.basic.ext.dp
import com.starblink.android.basic.ext.enableCorner
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.invisible
import com.starblink.android.basic.ext.toBean
import com.starblink.android.basic.ext.toJson
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.extension.businessSuffixId
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.util.FontUtil
import com.starblink.android.basic.util.ImageUtils
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.SubscribeBrandEvent
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.android.basic.widget.LoadingDialogManager
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.basic.ext.load
import com.starblink.basic.log.SKLogger
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.R
import com.starblink.basic.style.view.empty.SkEmptyView
import com.starblink.basic.util.CommUtils
import com.starblink.brand.BrandHelper
import com.starblink.brand.databinding.ActivityBrandDetailBinding
import com.starblink.brand.databinding.CellSimpleProductCardBrandBinding
import com.starblink.brand.databinding.ItemBrandCategoryBinding
import com.starblink.brand.databinding.ItemBrandsBrandBigBinding
import com.starblink.brand.databinding.ItemBrandsBrandSmallBinding
import com.starblink.brand.detail.bean.RvBrandCategoryEntry
import com.starblink.brand.detail.bean.RvTopBrandEntry
import com.starblink.brand.search.bean.RvProductWapper
import com.starblink.brand.widget.BrandChangeViewDialog
import com.starblink.library.widget.novice_guide.control.GuidePopStatusControl
import com.starblink.library.widget.sort.SortTypeEnum
import com.starblink.library.widget.sort.SortUtils
import com.starblink.rocketreserver.fragment.TopBrandInfoVOF
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlin.math.absoluteValue

/**品牌奥莱详情页面*/
@Route(path = RoutePage.Brand.BRAND_DETAIL)
class BrandDetailActivity : BaseTVMActivity<ActivityBrandDetailBinding, BrandDetailVM>() {

    override fun initViewBinding(): ActivityBrandDetailBinding =
        ActivityBrandDetailBinding.inflate(layoutInflater)

    @Autowired(name = RoutePage.Brand.ARG_BRAND_ID)
    @JvmField
    var brandId: String = ""

    @Autowired(name = RoutePage.Brand.ARG_EXPOSURE_BRAND_IDS)
    @JvmField
    var exposureBrandIds: ArrayList<Int>? = null

    @Autowired(name = RoutePage.Brand.ARG_IS_DISCOUNT_BRAND)
    @JvmField
    var isDiscountBrand: Boolean = true // 是否是折扣品牌，影响骨架图样式

    var isTopBrandBigView = true // true-品牌大视图
    var isShowBottomTopCorner = false // false-底部视图是否显示圆角，默认false

    private val TAG = "BrandDetailActivity"
    private val OFFSET1 = 137.dp2px()
    private val OFFSET2 = 134.dp2px()

    override fun initData() {
        super.initData()
        viewModel.brandId = if (brandId.isNullOrEmpty()) 0 else brandId.toInt()
        viewModel.exposureBrandIds = exposureBrandIds
    }

    override fun initView() {
        super.initView()

        initViewSkeleton()
        initViewCoordinatorLayout()
        initViewTopBrands()
        initViewSearch()
        initViewBrandCategory()
        initViewSort()
        initViewBrandProducts()

//        SKLogger.e("dss", "100.dp=" + 100.dp)
//        SKLogger.e("dss", "100.dp2px()=" + 100.dp2px())
//        SKLogger.e("dss", "CommUtils.dip2px(100)=" + CommUtils.dip2px(100))
//        SKLogger.e("dss", "CommUtils.px2dip(100)=" + CommUtils.px2dip(100))
//        SKLogger.e("dss", "100.px2dp()=" + 100.px2dp())
    }

    private fun initViewSkeleton() {
        viewBinding.layoutSkeleton.vSkeletonTopBrands.visibleOrGone(isDiscountBrand)
        viewBinding.layoutSkeleton.layoutBottomSkeleton.layoutSortSkeleton.vSortDiscount.visibleOrGone(
            isDiscountBrand
        )
    }

    // 初始化联动效果
    private fun initViewCoordinatorLayout() {
        viewBinding.layoutBrandsSmall.root.alpha = 0f
        viewBinding.layoutSort.vSearch.alpha = 0f
        viewBinding.appBarLayout.addOnOffsetChangedListener { appBarLayout: AppBarLayout, verticalOffset: Int ->
//            SKLogger.e(
//                "dss",
//                "getTotalScrollRangedp=${appBarLayout.totalScrollRange}px|${appBarLayout.totalScrollRange.px2dp()}dp,offSet=${verticalOffset}px|${verticalOffset.px2dp()}dp",
//            )

            // 内容视图圆角
            if (verticalOffset.absoluteValue < OFFSET1) {
                if (isShowBottomTopCorner) {
                    viewBinding.layoutBottomView.disableCorner()
                    isShowBottomTopCorner = false
                }
            } else {
                if (!isShowBottomTopCorner) {
                    viewBinding.layoutBottomView.enableCorner(24.dp, "top")
                    isShowBottomTopCorner = true
                }
            }

            // 顶部品牌列表折叠后视图透明度
            if (verticalOffset.absoluteValue > OFFSET2) {
                viewBinding.layoutBrandsSmall.root.visible()
                viewBinding.layoutSort.vSearch.visible()
                val alpha = maxOf(
                    (verticalOffset.absoluteValue - OFFSET2) * 1.0f / (appBarLayout.totalScrollRange - OFFSET2),
                    0.5f
                )
                viewBinding.layoutBrandsSmall.root.alpha = alpha
                viewBinding.layoutSort.vSearch.alpha = alpha
            } else {
                viewBinding.layoutBrandsSmall.root.invisible()
                viewBinding.layoutSort.vSearch.invisible()
                viewBinding.layoutBrandsSmall.root.alpha = 0f
                viewBinding.layoutSort.vSearch.alpha = 0f
            }

            // 折叠区域透明度
            val alpha = 1 - verticalOffset.absoluteValue * 1f / appBarLayout.totalScrollRange
            viewBinding.layoutBasicInfo.root.alpha = alpha
            viewBinding.layoutBrands.root.alpha = alpha
            if (alpha < 0.05f) {
                viewBinding.layoutBrands.root.invisible()
            } else {
                viewBinding.layoutBrands.root.visible()
            }

            // 页面内容滑动距离大于OFFSET时，显示返回按钮
            viewBinding.vReturnTop.visibleOrGone(verticalOffset.absoluteValue >= appBarLayout.totalScrollRange - 1)
        }

        // 返回顶部按钮
        viewBinding.vReturnTop.setOnClickListener {
            viewBinding.appBarLayout.setExpanded(true, true)
            viewBinding.rvProducts.scrollToPosition(0)
        }
    }

    private fun initViewBrandCategory() {
        viewBinding.rvCategory.linear().setup {
            addType<RvBrandCategoryEntry, ItemBrandCategoryBinding>(it)

            onBind {
                val viewBinding = getBinding<ItemBrandCategoryBinding>()
                val model = getModel<RvBrandCategoryEntry>()

                viewBinding.vName.text = model.name

                if (model.isSelected) {
                    viewBinding.root.setBackgroundColor(color(R.color.white))
                    viewBinding.vIcon.visible()
                    viewBinding.vName.setTextColor(CommUtils.getColor(com.starblink.basic.style.R.color.gu_text_primary))
                    viewBinding.vName.setTextSize(14F)
                    viewBinding.vName.typeface = FontUtil.getTypeface(FontUtil.MONTSERRAT_SEMIBOLD)
                } else {
                    viewBinding.root.setBackgroundColor(color(R.color.transparent))
                    viewBinding.vIcon.gone()
                    viewBinding.vName.setTextColor(CommUtils.getColor(com.starblink.basic.style.R.color.gu_text_secondary))
                    viewBinding.vName.setTextSize(12F)
                    viewBinding.vName.typeface = FontUtil.getTypeface(FontUtil.MONTSERRAT_MEDIUM)

                    // 选中项两侧Item，背景圆角
                    if (checkedPosition.size > 0) {
                        if (layoutPosition == checkedPosition[0] - 1) {
                            viewBinding.root.setBackgroundResource(com.starblink.brand.R.mipmap.bg_brand_category_up)
                        } else if (layoutPosition == checkedPosition[0] + 1) {
                            viewBinding.root.setBackgroundResource(com.starblink.brand.R.mipmap.bg_brand_category_down)
                        }
                    }
                }

                viewBinding.layoutBrandCategory.run {
                    // 埋点：品牌二级页-侧边类目
                    trackData(
                        page = SpmPageDef.BrandDetailPage,
                        element = SpmElementDef.Element_33049,
                        params = mapOf(
                            "thirdClassName" to model.name,
                            "brandName" to viewModel.brandName,
                            "index" to "${layoutPosition}"
                        ),
                        onlyHit = true,
                        businessSuffixID = businessSuffixId(model)
                    )
                }
            }

            // 点击品牌目录，触发选中/取消选中
            onClick(com.starblink.brand.R.id.layoutBrandCategory) {
                val model = getModel<RvBrandCategoryEntry>()
                // 如果未选中，则选中
                if (!model.isSelected) {
                    setChecked(layoutPosition, true)

                    // 选中后，重新请求数据
                    viewModel.categoryId = model.id
                    viewModel.refreshBrandProducts(showDialogLoading = true)

                    // 选中后，顶部视图收起
                    viewBinding.appBarLayout.setExpanded(false, true)
                    viewBinding.rvCategory.smoothScrollToPosition(layoutPosition)
                }
            }

            // 监听列表选中
            onChecked { position, isChecked, isAllChecked ->
                val model = getModel<RvBrandCategoryEntry>(position)
                model.isSelected = isChecked
                notifyItemChanged(position)

                // 选中某项，更新选中项和取消选中项两侧Item背景圆角
                if (position - 1 >= 0) {
                    notifyItemChanged(position - 1)
                }
                if (position + 1 < itemCount) {
                    notifyItemChanged(position + 1)
                }
            }
        }.apply {
            singleMode = true //目录支持单选
        }

        viewBinding.pageCategory.preloadIndex = 5 // 预加载倒数索引
        viewBinding.pageCategory.onLoadMore {
            viewModel.loadMoreBrandCategories()
        }
    }

    private fun initViewSearch() {
//        viewBinding.layoutSearch.layoutSearch.isEnabled = false
        viewBinding.layoutSearch.vSearch.run {
            click {
                // 点击搜索栏，跳转搜索页面
                navigationTo(RoutePage.Brand.BRAND_SEARCH) {
                    withString(RoutePage.Brand.ARG_BRAND_ID, brandId)
                    withString(RoutePage.Brand.ARG_BRAND_NAME, viewModel.brandName)
                    withBoolean(RoutePage.Brand.ARG_IS_DISCOUNT_BRAND, viewModel.isDiscountBrand)
                }

                // 埋点:点击搜索栏
                SpmTrackHandler.addSingleTrackData(
                    SkAntEntity(
                        spmCnt = GTrackerAssistUtils.fetchElementValue(
                            SpmPageDef.BrandDetailPage,
                            SpmElementDef.ELE_33002
                        ),
                        params = mapOf(
                            "brandName" to (viewModel.brandName),
                            "brandId" to brandId
                        )
                    )
                )
            }
        }
    }

    private fun initViewSort() {
        viewBinding.layoutSort.vSortPrice.setOnClickListener {
            if (viewModel.sortType == SortTypeEnum.PRICE_L2H) {
                // 第二次点击Price，显示H2L
                viewModel.sortType = SortTypeEnum.PRICE_H2L
                viewBinding.layoutSort.vSortPrice.icon =
                    CommUtils.getDrawable(com.starblink.library.widget.R.drawable.ic_sort_discount_h2l1)
            } else if (viewModel.sortType == SortTypeEnum.PRICE_H2L) {
                // 第三次点击Price，显示默认
                viewModel.sortType = SortTypeEnum.DEFAULT
                SortUtils.setSortViewSelected(viewBinding.layoutSort.vSortPrice, false)
            } else {
                // 第一次点击Price，显示L2H

                // 取消Discount排序
                if (viewModel.sortType != SortTypeEnum.DEFAULT) {
                    SortUtils.setSortViewSelected(viewBinding.layoutSort.vSortDiscount, false)
                }

                viewModel.sortType = SortTypeEnum.PRICE_L2H
                SortUtils.setSortViewSelected(viewBinding.layoutSort.vSortPrice, true)
                viewBinding.layoutSort.vSortPrice.icon =
                    CommUtils.getDrawable(com.starblink.library.widget.R.drawable.ic_sort_discount_l2h1)
            }
            // 重新加载数据
            viewModel.refreshBrandProducts(showDialogLoading = true)
        }

        viewBinding.layoutSort.vSortDiscount.setOnClickListener {
            if (viewModel.sortType == SortTypeEnum.DISCOUNT_H2L) {
                // 第二次点击Discount，显示L2H
                viewModel.sortType = SortTypeEnum.DISCOUNT_L2H
                viewBinding.layoutSort.vSortDiscount.icon =
                    CommUtils.getDrawable(com.starblink.library.widget.R.drawable.ic_sort_discount_l2h1)
            } else if (viewModel.sortType == SortTypeEnum.DISCOUNT_L2H) {
                // 第三次点击Discount，显示默认
                viewModel.sortType = SortTypeEnum.DEFAULT
                SortUtils.setSortViewSelected(viewBinding.layoutSort.vSortDiscount, false)
            } else {
                // 第一次点击Discount，显示H2L

                // 取消Price排序
                if (viewModel.sortType != SortTypeEnum.DEFAULT) {
                    SortUtils.setSortViewSelected(viewBinding.layoutSort.vSortPrice, false)
                }

                viewModel.sortType = SortTypeEnum.DISCOUNT_H2L
                SortUtils.setSortViewSelected(viewBinding.layoutSort.vSortDiscount, true)
                viewBinding.layoutSort.vSortDiscount.icon =
                    CommUtils.getDrawable(com.starblink.library.widget.R.drawable.ic_sort_discount_h2l1)
            }
            // 重新加载数据
            viewModel.refreshBrandProducts(showDialogLoading = true)
        }

        viewBinding.layoutSort.vSearch.setOnClickListener {
            // 点击搜索栏，跳转搜索页面
            navigationTo(RoutePage.Brand.BRAND_SEARCH) {
                withString(RoutePage.Brand.ARG_BRAND_ID, brandId)
                withString(RoutePage.Brand.ARG_BRAND_NAME, viewModel.brandName)
                withBoolean(RoutePage.Brand.ARG_IS_DISCOUNT_BRAND, viewModel.isDiscountBrand)
            }
        }

        viewBinding.layoutSort.vSwitchView.setImageResource(if (BrandHelper.showSimpleViewInBrandDetail) com.starblink.brand.R.drawable.ic_brand_change_view_simple else com.starblink.brand.R.drawable.ic_brand_change_view_origin)
        viewBinding.layoutSort.vSwitchView.click {
            val dialog =
                navigationTo(RoutePage.Brand.DIALOG_CHANGE_VIEW) {
                    withBoolean(
                        RoutePage.Brand.ARG_SIMPLE_VIEW,
                        BrandHelper.showSimpleViewInBrandDetail
                    )
                } as BrandChangeViewDialog
            dialog.show(supportFragmentManager, "BrandChangeViewDialog")
        }
        supportFragmentManager.setFragmentResultListener(
            BrandChangeViewDialog.RESULT_SIMPLE_VIEW,
            this
        ) { _, bundle ->
            val res = bundle.getBoolean(BrandChangeViewDialog.ARG_RESULT, false)
            if (res != BrandHelper.showSimpleViewInBrandDetail) {
                // 修改了视图模式，更新数据
                BrandHelper.showSimpleViewInBrandDetail = res
                FlowBus.boolFlowBusNotify(FlowConst.BRAND_CHANGE_VIEW_MODE)
            }
        }

        // 事件处理
        FlowBus.with<Boolean>(FlowConst.BRAND_CHANGE_VIEW_MODE)
            .register(this) { event ->
                MainScope().launch {
                    viewBinding.layoutSort.vSwitchView.setImageResource(if (BrandHelper.showSimpleViewInBrandDetail) com.starblink.brand.R.drawable.ic_brand_change_view_simple else com.starblink.brand.R.drawable.ic_brand_change_view_origin)
                    viewBinding.rvProducts.bindingAdapter.models?.forEach {
                        if (it is RvProductWapper) {
                            it.showSimpleView = BrandHelper.showSimpleViewInBrandDetail
                        }
                    }
                    viewBinding.rvProducts.bindingAdapter.notifyDataSetChanged()
                }
            }
    }

    private fun initViewBrandProducts() {
        viewBinding.rvProducts.grid(2).divider {
            setDivider(7, true)
            orientation = DividerOrientation.VERTICAL
        }.setup {
            addType<RvProductWapper, CellSimpleProductCardBrandBinding>(it)

            onBind {
                when (itemViewType) {
                    com.starblink.brand.R.layout.cell_simple_product_card_brand -> {
                        val viewBinding = getBinding<CellSimpleProductCardBrandBinding>()
                        val model = getModel<RvProductWapper>()

                        viewBinding.card.bindProduct(
                            activity = this@BrandDetailActivity,
                            position = layoutPosition,
                            productWapper = model,
                            trackPage = SpmPageDef.BrandDetailPage,
                            brandName = viewModel.brandName,
                            brandId = viewModel.brandId
                        )
                    }
                }
            }
        }

        viewBinding.pageProducts.onEmpty {
            val emptyView = findViewById<SkEmptyView>(R.id.vEmptyView)
            emptyView?.let {
                it.text2 = "No items found"
            }
        }

        viewBinding.pageProducts.preloadIndex = 5 // 预加载倒数索引
        viewBinding.pageProducts.onRefresh {
            viewModel.refreshBrandProducts()
        }
        viewBinding.pageProducts.onLoadMore {
            viewModel.loadMoreBrandProducts()
        }
    }

    private fun initViewTopBrands() {
        fun View.viewAll() {
            // 埋点：品牌二级页-品牌切换
            trackData(
                page = SpmPageDef.BrandDetailPage,
                element = SpmElementDef.ELE_30060,
                params = mapOf("tabName" to "view all", "brandId" to brandId),
                businessSuffixID = businessSuffixId("${brandId}")
            )
            click {
                navigationTo(RoutePage.Brand.BRAND_ALL)
            }
        }
        viewBinding.layoutBrands.layoutViewAll.run {
            viewAll()
        }
        viewBinding.layoutBrandsSmall.layoutViewAll.run {
            viewAll()
        }

        fun selectBrandItemAfterClick(model: RvTopBrandEntry, layoutPosition: Int) {
            // 仅当品牌未选中，点击时选中
            if (!model.isSelected) {
                model.brandVO?.let {
                    // 选中品牌
                    viewBinding.layoutBrandsSmall.rvBrands.bindingAdapter.setChecked(
                        layoutPosition,
                        true
                    )
                    viewBinding.layoutBrands.rvBrands.bindingAdapter.setChecked(
                        layoutPosition,
                        true
                    )

                    // 选中后，切换当前页面品牌
                    viewModel.brandId = it.brandId!! as Int
                    viewModel.brandName = it.name ?: ""
                    viewModel.isDiscountBrand = it.brandDiscount != null
                    changeBrand()

                    // 先显示已有数据，随后重新加载成功后在更新
                    setViewBasicInfo(
                        it.brandDiscount != null,
                        it!!.toJson().toBean<TopBrandInfoVOF>()
                    )

                    // 点击项滚动到左边第一个
                    (viewBinding.layoutBrands.rvBrands.layoutManager as? LinearLayoutManager)?.scrollToPositionWithOffset(
                        layoutPosition,
                        0
                    )
                    (viewBinding.layoutBrandsSmall.rvBrands.layoutManager as? LinearLayoutManager)?.scrollToPositionWithOffset(
                        layoutPosition,
                        0
                    )

                    // 重置排序视图
                    SortUtils.setSortViewSelected(
                        viewBinding.layoutSort.vSortDiscount,
                        false
                    )
                    SortUtils.setSortViewSelected(viewBinding.layoutSort.vSortPrice, false)
                }
            }
        }

        viewBinding.layoutBrands.rvBrands.linear(orientation = RecyclerView.HORIZONTAL)
            .divider {
                setDivider(8, true)
                endVisible = true
                setColor(Color.TRANSPARENT)
            }.setup {
                addType<RvTopBrandEntry, ItemBrandsBrandBigBinding>(it)

                onBind {
                    val viewBinding = getBinding<ItemBrandsBrandBigBinding>()
                    val model = getModel<RvTopBrandEntry>()

                    if (model.isSelected) {
                        // 选中视图
                        viewBinding.layoutSelectedBig.visible()
                        viewBinding.layoutUnselected.gone()
                        viewBinding.layoutSelectedBigBg.imageTintList =
                            ColorStateList.valueOf(getBackgroundTintColor(layoutPosition))

                        viewBinding.vNameSelectedBig.visibleOrGone(
                            model.brandVO?.name.isNullOrEmpty().not()
                        ) {
                            text = model.brandVO?.name
                        }
                        viewBinding.vUpToSelectedBig.visibleOrGone(model.brandVO?.brandDiscount != null)
                        viewBinding.vDiscountSelectedBig.visibleOrGone(model.brandVO?.brandDiscount != null) {
                            text = "${model.brandVO?.brandDiscount?.toString()}%"
                        }
                        ImageUtils.loadImage(
                            mContext,
                            model.brandVO?.brandImg,
                            viewBinding.vIconSelectedBig,
                            RequestOptions()
                                .placeholder(com.starblink.brand.R.drawable.ic_svg_top_brand_image_placeholder)
                                .error(com.starblink.brand.R.drawable.ic_svg_top_brand_image_placeholder)
                                .format(DecodeFormat.PREFER_RGB_565)
                        )
                    } else {
                        // 未选中视图
                        viewBinding.layoutSelectedBig.gone()
                        viewBinding.layoutUnselected.visible()
                        viewBinding.layoutUnselected.background.setTint(
                            getBackgroundTintColor(
                                layoutPosition
                            )
                        )
                        viewBinding.vUpToUnselected.visibleOrGone(model.brandVO?.brandDiscount != null)
                        viewBinding.vDiscountUnselected.visibleOrGone(model.brandVO?.brandDiscount != null) {
                            text = "${model.brandVO?.brandDiscount?.toString()}%"
                        }
                        viewBinding.vNameUnselected.visibleOrGone(
                            model.brandVO?.name.isNullOrEmpty().not()
                        ) {
                            text = model.brandVO?.name
                        }
                        ImageUtils.loadImage(
                            mContext,
                            model.brandVO?.brandImg,
                            viewBinding.vIconUnselected,
                            RequestOptions()
                                .placeholder(com.starblink.brand.R.drawable.ic_svg_top_brand_image_placeholder)
                                .error(com.starblink.brand.R.drawable.ic_svg_top_brand_image_placeholder)
                                .format(DecodeFormat.PREFER_RGB_565)
                        )
                    }

                    viewBinding.layoutBrandBig.run {
                        // 埋点：品牌二级页-品牌切换
                        if (model.brandVO?.name.isNullOrEmpty().not()) {
                            trackData(
                                page = SpmPageDef.BrandDetailPage,
                                element = SpmElementDef.ELE_30060,
                                params = mapOf(
                                    "tabName" to model.brandVO?.name!!,
                                    "brandId" to brandId
                                ),
                                businessSuffixID = businessSuffixId(model)
                            )
                        }
                    }
                }

                // 点击品牌列表项，触发选中/取消选中
                onClick(com.starblink.brand.R.id.layoutBrandBig) {
                    val model = getModel<RvTopBrandEntry>()
                    selectBrandItemAfterClick(model, layoutPosition)
                }

                // 监听列表选中
                onChecked { position, isChecked, isAllChecked ->
                    val model = getModel<RvTopBrandEntry>(position)
                    model.isSelected = isChecked
                    notifyItemChanged(position)
                }
            }.apply {
                singleMode = true //品牌支持单选
            }

        viewBinding.layoutBrandsSmall.rvBrands.linear(orientation = RecyclerView.HORIZONTAL)
            .divider {
                setDivider(8, true)
                endVisible = true
                setColor(Color.TRANSPARENT)
            }.setup {
                addType<RvTopBrandEntry, ItemBrandsBrandSmallBinding>(it)

                onBind {
                    val viewBinding = getBinding<ItemBrandsBrandSmallBinding>()
                    val model = getModel<RvTopBrandEntry>()
                    var layoutView: View? = null

                    if (model.isSelected) {
                        // 选中视图
                        viewBinding.layoutSelectedSmall.visible()
                        viewBinding.layoutUnselected.gone()

                        layoutView = viewBinding.layoutSelectedSmall

                        viewBinding.vNameSelectedSmall.visibleOrGone(
                            model.brandVO?.name.isNullOrEmpty().not()
                        ) {
                            text = model.brandVO?.name
                        }
                        viewBinding.vUpToSelectedSmall.visibleOrGone(model.brandVO?.brandDiscount != null)
                        viewBinding.vDiscountSelectedSmall.visibleOrGone(model.brandVO?.brandDiscount != null) {
                            text = "${model.brandVO?.brandDiscount?.toString()}%"
                        }
                        ImageUtils.loadImage(
                            mContext,
                            model.brandVO?.brandImg,
                            viewBinding.vIconSelectedSmall,
                            RequestOptions()
                                .placeholder(com.starblink.brand.R.drawable.ic_svg_top_brand_image_placeholder)
                                .error(com.starblink.brand.R.drawable.ic_svg_top_brand_image_placeholder)
                                .format(DecodeFormat.PREFER_RGB_565)
                        )
                    } else {
                        // 未选中视图
                        viewBinding.layoutSelectedSmall.gone()
                        viewBinding.layoutUnselected.visible()
                        layoutView = viewBinding.layoutUnselected
                        viewBinding.vNameUnselected.visibleOrGone(
                            model.brandVO?.name.isNullOrEmpty().not()
                        ) {
                            text = model.brandVO?.name
                        }
                        ImageUtils.loadImage(
                            mContext,
                            model.brandVO?.brandImg,
                            viewBinding.vIconUnselected,
                            RequestOptions()
                                .placeholder(com.starblink.brand.R.drawable.ic_svg_top_brand_image_placeholder)
                                .error(com.starblink.brand.R.drawable.ic_svg_top_brand_image_placeholder)
                                .format(DecodeFormat.PREFER_RGB_565)
                        )
                    }

                    layoutView?.run { background.setTint(getBackgroundTintColor(layoutPosition)) }

                    viewBinding.layoutBrandSmall.run {
                        // 埋点：品牌二级页-品牌切换
                        if (model.brandVO?.name.isNullOrEmpty().not()) {
                            trackData(
                                page = SpmPageDef.BrandDetailPage,
                                element = SpmElementDef.ELE_30060,
                                params = mapOf(
                                    "tabName" to model.brandVO?.name!!,
                                    "brandId" to brandId
                                ),
                                businessSuffixID = businessSuffixId(model)
                            )
                        }
                    }
                }

                // 点击品牌列表项，触发选中/取消选中
                onClick(com.starblink.brand.R.id.layoutBrandSmall) {
                    val model = getModel<RvTopBrandEntry>()
                    selectBrandItemAfterClick(model, layoutPosition)
                    // 顶部视图展开
                    viewBinding.appBarLayout.setExpanded(true, true)
                }

                // 监听列表选中
                onChecked { position, isChecked, isAllChecked ->
                    val model = getModel<RvTopBrandEntry>(position)
                    model.isSelected = isChecked
                    notifyItemChanged(position)
                }
            }.apply {
                singleMode = true //品牌支持单选
            }

        viewBinding.layoutBrands.pageBrands.setOnLoadMoreListener {
            SKLogger.e("dss3", "viewModel.loadMoreTopBrands()")
            viewModel.loadMoreTopBrands()
        }

        // 顶部品牌列表，双列表联动
        viewBinding.layoutBrands.rvBrands.addOnScrollListener(object :
            RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                when (newState) {
                    RecyclerView.SCROLL_STATE_IDLE -> {
                        // 仅当列表停止滚动时联动（性能更好）
                        (recyclerView.layoutManager as? LinearLayoutManager)?.let {
                            val lastPosition = it.findFirstVisibleItemPosition()
                            var lastOffset = it.findViewByPosition(lastPosition)?.left ?: 0
                            (viewBinding.layoutBrandsSmall.rvBrands.layoutManager as? LinearLayoutManager)?.scrollToPositionWithOffset(
                                lastPosition,
                                lastOffset
                            )
                        }
                    }
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
            }
        })

        viewBinding.layoutBrandsSmall.rvBrands.addOnScrollListener(object :
            RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                when (newState) {
                    RecyclerView.SCROLL_STATE_IDLE -> {
                        (recyclerView.layoutManager as? LinearLayoutManager)?.let {
                            // 仅当列表停止滚动时联动（性能更好）
                            val lastPosition = it.findFirstVisibleItemPosition()
                            var lastOffset = it.findViewByPosition(lastPosition)?.left ?: 0
                            (viewBinding.layoutBrands.rvBrands.layoutManager as? LinearLayoutManager)?.scrollToPositionWithOffset(
                                lastPosition,
                                lastOffset
                            )

                            // 滑动到底部，尝试加载更多
                            if (it.findLastVisibleItemPosition() == it.itemCount - 1 && !viewBinding.layoutBrands.pageBrands.isLoading) {
                                viewBinding.layoutBrands.pageBrands.autoLoadMore()
                                SKLogger.e(
                                    "dss3",
                                    " viewBinding.layoutBrands.pageBrands.autoLoadMore()"
                                )
                            }
                        }
                    }
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
            }
        })
    }

    private fun changeBrand() {
        viewBinding.layoutSkeletonChangeBrand.visible()
        viewModel.changeBrand()
    }


    override fun initObservable() {
        super.initObservable()
        // 首页加载
        viewModel.pageRefreshDataLD.observe(this) {
            // 接口异常，显示错误视图
            if (it.excludeTopBrands) {
                // 品牌切换
                if (it.brandInfo == null
                    || it.brandProducts == null
                ) {
                    SKLogger.e("dss2", "22222, viewModel.pageRefreshDataLD.observe")
                    showErrorViewForChangeBrand()
                    return@observe
                }
            } else {
                // 加载首页
                if (it.brandInfo == null
                    || (it.discountBrand && it.topBrands.isNullOrEmpty())
                    || it.brandProducts == null
                ) {
                    showErrorViewForFirstPage()
                    return@observe
                }

                // 页面曝光
                pageExposure(
                    SpmPageDef.BrandDetailPage,
                    params = mapOf("brandName" to (viewModel.brandName), "brandId" to brandId)
                )

                setViewTopBrands(it.discountBrand, it.topBrands)
            }

            setViewBrandCategories(it.brandCategories)
            setViewSort(it.discountBrand)
            setViewBasicInfo(it.discountBrand, it.brandInfo!!)
            setViewBrandProducts(it.brandProducts!!)
            showContentView()
        }

        // 品牌商品
        viewModel.refreshBrandProductsLD.observe(this) {
            viewBinding.pageProducts.index = PageRefreshLayout.startIndex
            viewBinding.pageProducts.addData(it)
        }
        viewModel.loadMoreBrandProductsLD.observe(this) {
            viewBinding.pageProducts.addData(it) {
                it.isNotEmpty()
            }
        }

        // 顶部折扣品牌
        viewModel.loadMoreTopBrandsLD.observe(this) {
            SKLogger.e("dss3", "viewModel.loadMoreTopBrandsLD.observe(this)")
            viewBinding.layoutBrands.rvBrands.bindingAdapter.addModels(it)
            if (it.isEmpty()) {
                viewBinding.layoutBrands.pageBrands.finishLoadMoreWithNoMoreData()
            } else {
                // 刷新ViewALL小视图数据
                viewBinding.layoutBrandsSmall.rvBrands.bindingAdapter.notifyItemRangeInserted(
                    viewBinding.layoutBrandsSmall.rvBrands.bindingAdapter.modelCount - it.size,
                    it.size
                )
                viewBinding.layoutBrands.pageBrands.finishLoadMore()
            }
        }

        // 品牌目录
        viewModel.loadMoreBrandCategoriesLD.observe(this) {
            viewBinding.pageCategory.addData(it) {
                it.isNotEmpty()
            }
        }

        // 异常处理
        viewModel.mLoadActionLiveData.observe(this) {
            when (it.action) {
                LoadAction.STATE_ERROR -> {
                    when (it.errorCode) {
                        BrandDetailVM.ERROR_LOAD_FIRST_PAGE_DATA_FAIL -> {
                            showErrorViewForFirstPage()
                        }

                        BrandDetailVM.ERROR_LOAD_BRAND_PRODUCTS_FAIL -> {
                            viewBinding.pageProducts.showError()
                        }

                        BrandDetailVM.ERROR_LOAD_MORE_BRAND_CATEGORIES_FAIL -> {
                            viewBinding.pageCategory.finish(false)
                        }

                        BrandDetailVM.ERROR_LOAD_MORE_TOP_BRANDS_FAIL -> {
                            viewBinding.layoutBrands.pageBrands.finishLoadMore()
                        }

                        BrandDetailVM.ERROR_LOAD_CHANGE_BRAND_DATA_FAIL -> {
                            showErrorViewForChangeBrand()
                        }
                    }
                }
            }
        }

        initEvents()
    }

    private fun setViewSort(discountBrand: Boolean) {
        viewBinding.layoutSort.vSortDiscount.visibleOrGone(discountBrand)
    }

    private fun setViewBrandProducts(brandProducts: List<RvProductWapper>) {
        viewBinding.pageProducts.index = PageRefreshLayout.startIndex // 切换品牌时，重置数据
        viewBinding.pageProducts.addData(brandProducts)
        viewBinding.rvProducts.scrollToPosition(0) // 切换品牌时，回到顶部
    }

    private fun setViewTopBrands(discountBrand: Boolean, topBrands: List<RvTopBrandEntry>?) {
        if (!discountBrand) {
            // 非折扣品牌，不显示TopBrands
            viewBinding.layoutBrands.root.gone()
            viewBinding.layoutBrandsSmall.root.gone()
            viewBinding.collapsingToolbarLayout.minimumHeight = 0
        } else {
            // 折扣品牌，显示TopBrands
            topBrands?.let {
                //!!!注意：viewBinding.layoutBrands.rvBrands和viewBinding.layoutBrandsSmall.rvBrands列表的数据源相同，加载更多不要重复添加数据
                viewBinding.layoutBrands.rvBrands.models = topBrands
                viewBinding.layoutBrands.rvBrands.bindingAdapter.setChecked(0, true)
                viewBinding.layoutBrandsSmall.rvBrands.models = topBrands
                viewBinding.layoutBrandsSmall.rvBrands.bindingAdapter.setChecked(0, true)
            }
        }
    }

    private fun showLogoTextIcon(name: String) {
        viewBinding.layoutBasicInfo.ivIcon.gone()
        viewBinding.layoutBasicInfo.tvIcon.visible()
        viewBinding.layoutBasicInfo.tvIcon.text =
            name.first().toString().uppercase()
    }

    // 设置品牌基础信息视图
    private fun setViewBasicInfo(discountBrand: Boolean, brandInfo: TopBrandInfoVOF) {
        if (brandInfo.logo.isNullOrEmpty()) {
            showLogoTextIcon(brandInfo.name ?: "")
        } else {
            viewBinding.layoutBasicInfo.ivIcon.load(brandInfo.logo, errorCall = {
                showLogoTextIcon(brandInfo.name ?: "")
            })
        }

        viewBinding.layoutBasicInfo.tvTitle.text = brandInfo.name
        viewBinding.layoutBrandTopBar.vTitleTop.text = brandInfo.name ?: "Brand Outlets"
        brandInfo.name?.let {
            viewBinding.layoutSearch.vSearch.text = "Search in ${it}"
        }

        // 品牌底图
        ImageUtils.loadImage(
            mContext,
            brandInfo.brandImg,
            viewBinding.ivTopBg,
            RequestOptions()
                .placeholder(com.starblink.brand.R.drawable.ic_svg_top_brand_image_placeholder)
                .error(com.starblink.brand.R.drawable.ic_svg_top_brand_image_placeholder)
                .format(DecodeFormat.PREFER_RGB_565)
        )
        //品牌订阅
        updateSubscribeState(brandInfo)
        viewBinding.layoutBasicInfo.btnFollow.run {
            setOnClickListener {
                CommonMutateManage.subscribeOrNotBrand(
                    ctx = commContext(),
                    subOrNot = brandInfo.hasSub ?: false,
                    brandId = brandInfo.brandId ?: ""
                ) { hasSub ->
                    brandInfo.apolloValue("hasSub", hasSub)
                    updateSubscribeState(brandInfo)

                    // 埋点:店铺订阅-点击
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                SpmPageDef.BrandDetailPage,
                                SpmElementDef.Element_33087
                            ),
                            params = mapOf(
                                "brandName" to (brandInfo.name ?: ""),
                                "result" to "${if (hasSub == true) "1" else "0"}",
                                "brandId" to brandId
                            )
                        )
                    )
                }
            }
        }

        viewBinding.layoutBasicInfo.btnFollow.post {
            if (!brandInfo.hasSub) {
                GuidePopStatusControl.popBrandDetailsFollowGuide(
                    guideType = TAG,
                    tarView = viewBinding.layoutBasicInfo.btnFollow,
                    bootView = viewBinding.brandRoot as ViewGroup
                )
            }
        }
    }

    //更新订阅状态
    private fun updateSubscribeState(brandInfo: TopBrandInfoVOF) {
        if (brandInfo.hasSub) {
            viewBinding.layoutBasicInfo.btnFollow.setImageResource(com.starblink.library.widget.R.mipmap.ic_brand_detail_following)
        } else {
            viewBinding.layoutBasicInfo.btnFollow.setImageResource(com.starblink.library.widget.R.mipmap.ic_brand_detail_follow)
        }
    }

    // 设置品牌目录视图
    private fun setViewBrandCategories(brandCategories: List<RvBrandCategoryEntry>?) {
        if (brandCategories == null) {
            // 无目录不显示
            viewBinding.pageCategory.gone()
            viewBinding.layoutBrandProducts.setPadding(12.dp, 0, 0, 0)
            viewBinding.rvProducts.setPadding(0, 0, 12.dp, 0)
            while (viewBinding.rvProducts.itemDecorationCount > 0) {
//                SKLogger.e("dss3", "removeItemDecorationAt111")
                viewBinding.rvProducts.removeItemDecorationAt(0)
            }
            viewBinding.rvProducts.divider {
                setDivider(9, true)
                orientation = DividerOrientation.VERTICAL
            }
        } else {
            // 显示目录
            viewBinding.pageCategory.visible()
            viewBinding.layoutBrandProducts.setPadding(7.dp, 0, 0, 0)
            viewBinding.rvProducts.setPadding(0, 0, 7.dp, 0)
            while (viewBinding.rvProducts.itemDecorationCount > 0) {
//                SKLogger.e("dss3", "removeItemDecorationAt222")
                viewBinding.rvProducts.removeItemDecorationAt(0)
            }
            viewBinding.rvProducts.divider {
                setDivider(7, true)
                orientation = DividerOrientation.VERTICAL
            }
            viewBinding.pageCategory.index = PageRefreshLayout.startIndex  // 切换品牌时，重置数据
            viewBinding.pageCategory.addData(brandCategories)
            viewBinding.rvCategory.bindingAdapter.setChecked(0, true)
            viewBinding.rvCategory.scrollToPosition(0) // 切换品牌时，回到顶部
        }
    }

    private fun loadPageData() {
        viewBinding.layoutSkeleton.root.visible()
        viewModel.loadPageData(showGlobalLoading = false)
    }

    private fun showContentView() {
        LoadingDialogManager.get().dismissLoading()
        viewBinding.layoutBottomView.visible()
        viewBinding.layoutErrorViewFirstPage.root.gone()
        viewBinding.vErrorViewChangeBrand.gone()
        viewBinding.layoutSkeleton.root.gone()
        viewBinding.layoutSkeletonChangeBrand.gone()
    }

    // 显示首页加载错误视图
    private fun showErrorViewForFirstPage() {
        LoadingDialogManager.get().dismissLoading()
        viewBinding.layoutSkeleton.root.gone()
        viewBinding.layoutErrorViewFirstPage.root.visible()

        // 使用默认值
        viewBinding.layoutErrorViewFirstPage.vErrorViewFirstPage.btnShown = true
        viewBinding.layoutErrorViewFirstPage.vErrorViewFirstPage.btnText = "Reload"
        viewBinding.layoutErrorViewFirstPage.vErrorViewFirstPage.onBtnClick = {
            loadPageData()
        }
    }

    // 显示切换品牌错误视图
    private fun showErrorViewForChangeBrand() {
        LoadingDialogManager.get().dismissLoading()
        viewBinding.vErrorViewChangeBrand.visible()
        viewBinding.layoutBottomView.gone()
        viewBinding.layoutSkeletonChangeBrand.gone()

        // 使用默认值
        viewBinding.vErrorViewChangeBrand.btnShown = true
        viewBinding.vErrorViewChangeBrand.btnText = "Reload"
        viewBinding.vErrorViewChangeBrand.onBtnClick = {
            changeBrand()
        }
    }

    private fun initEvents() {
        // 事件处理：关注品牌事件
        FlowBus.with<SubscribeBrandEvent>(FlowConst.SUBSCRIBE_BRAND_EVENT)
            .register(this) { event ->
                MainScope().launch {
                    if (event.brandId == null) {
                        return@launch
                    }

                    // 修正当前品牌
                    if (event.brandId == viewModel.brandId && viewModel.pageRefreshDataLD.value?.brandInfo != null
                        && event.hasSub != viewModel.pageRefreshDataLD.value?.brandInfo?.hasSub
                    ) {
                        viewModel.pageRefreshDataLD.value!!.brandInfo!!.apolloValue(
                            "hasSub",
                            event.hasSub
                        )
                        updateSubscribeState(viewModel.pageRefreshDataLD.value!!.brandInfo!!)
                    }

                    // 修改头部折扣品牌数据
                    viewBinding.layoutBrands.rvBrands.models?.let {
                        for ((index, model) in it.withIndex()) {
                            if (model is RvTopBrandEntry && model.brandVO != null
                                && model.brandVO.brandId == event.brandId && event.hasSub != model.brandVO.hasSub
                            ) {
                                model.brandVO.apolloValue("hasSub", event.hasSub)
                            }
                        }
                    }
                }
            }
    }

    override fun initLoad() {
        super.initLoad()
        loadPageData()
    }

    /**
     * 获取品牌列表项背景色值（5色循环）
     */
    private fun getBackgroundTintColor(position: Int): Int {
        return CommUtils.getColor(
            when (position % 5) {
                0 -> R.color.gu_yellow_100
                1 -> R.color.gu_blue_100
                2 -> R.color.gu_light_blue_100
                3 -> R.color.gu_purple_100
                4 -> R.color.gu_red_100
                else -> R.color.gu_yellow_100
            }
        )
    }

    override fun onPause() {
        super.onPause()
        pageDisappear(
            SpmPageDef.BrandDetailPage,
            params = mapOf("brandName" to (viewModel.brandName), "brandId" to brandId)
        )
    }
}